const bodyParser = require("body-parser");

// 导入各个控制器
const authController = require("./authController");
const exerciseController = require("./exerciseController");
const nutritionController = require("./nutritionController");

module.exports = (app) => {
  const express = require("express");
  
  const router = express.Router({
    mergeParams: true,
  });
  
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());

  // ==================== 认证相关路由 ====================
  // 登录
  app.get("/web/api/login", authController.login);

  // 注册/更新用户信息
  app.post("/web/api/register", authController.register);

  // ==================== 运动相关路由 ====================
  // 获取运动步数
  app.post("/web/api/run", exerciseController.getRunData);

  // ==================== 通用CRUD路由 ====================
  // 更新数据
  router.put("/", nutritionController.updateData);

  // 获取数据
  router.get("/", nutritionController.getData);

  // ==================== 资源路由中间件 ====================
  // 动态资源路由，自动加载对应的模型
  app.use(
    "/web/api/:resource",
    async (req, res, next) => {
      const modelName = require("inflection").classify(req.params.resource);
      req.Model = require(`../../models/${modelName}`);
      next();
    },
    router
  );
};
